package controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.WebsiteModel;

import entities.Website;
import forms.WebsiteForm;

public class WebsiteEditServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		WebsiteModel websiteModel = WebsiteModel.getInstance();
		Website website = websiteModel.get(id);
		
		if (website == null) {
			response.sendRedirect("/website/list");
			return;
		}
		
		request.setAttribute("check", check);
		request.setAttribute("website", website);
		request.setAttribute("form", "edit");
		try {
			request.getRequestDispatcher("/pages/website_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		WebsiteModel websiteModel = WebsiteModel.getInstance();
		Website website = websiteModel.get(id);
		
		if (website == null) {
			response.sendRedirect("/website/list");
			return;
		}
		
		//Get value form and check valid
		TreeMap form = WebsiteForm.checkValid(request, website);
		website = (Website) form.get("website");
		TreeMap<String, String>  check = (TreeMap) form.get("checkValid");
		
		//Save data
		if (check.size() == 0){
			websiteModel.insert(website);
			request.setAttribute("success", "Edit success website " + website.getId());
		}
		
		request.setAttribute("check", check);
		request.setAttribute("website", website);
		request.setAttribute("form", "edit");
		try {
			request.getRequestDispatcher("/pages/website_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
